﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace DownloadTED
{
	public static class TedUtility
	{
		internal static TedVideo Create(string url)
		{
			string infoUrl= url;
			string infoHtml=GetHttpHtml(infoUrl);
			TedVideo item=new TedVideo();
			item.Code = int.Parse(Regex.Match(infoHtml, @"ti\:\""(?<value>\d+)\"",").Groups["value"].Value);
			item.VideoHighQualityUrl = Regex.Match(infoHtml, @"hs\:\""(?<value>[^\""]*)\"",").Groups["value"].Value;
			item.VideoMediumQualityUrl = Regex.Match(infoHtml, @"ms\:\""(?<value>[^\""]*)\"",").Groups["value"].Value;
			item.VideoLowQualityUrl = Regex.Match(infoHtml, @"ls\:\""(?<value>[^\""]*)\"",").Groups["value"].Value;
			item.IntroDuration = int.Parse(Regex.Match(infoHtml, @"introDuration\:(?<value>\d+),").Groups["value"].Value);
			string _lang= Uri.UnescapeDataString(Regex.Match(infoHtml, "languages\\:\\\"(?<value>[^\\\"]*)\\\",").Value);
			foreach (Match langMatch in Regex.Matches(_lang, "\\\"LanguageCode\\\"\\:\\\"(?<value>\\w+)\\\""))
				item.Languages.Add(langMatch.Groups["value"].Value);

			return item;
		}

		internal static TedVideo Create(int id)
		{
			string infoUrl= string.Format("http://www.ted.com/talks/view/id/{0}", id);
			string infoHtml=GetHttpHtml(infoUrl);
			TedVideo item=new TedVideo();
			item.Code = id;
			item.VideoHighQualityUrl = Regex.Match(infoHtml, @"hs\:\""(?<value>[^\""]*)\"",").Groups["value"].Value;
			item.VideoMediumQualityUrl = Regex.Match(infoHtml, @"ms\:\""(?<value>[^\""]*)\"",").Groups["value"].Value;
			item.VideoLowQualityUrl = Regex.Match(infoHtml, @"ls\:\""(?<value>[^\""]*)\"",").Groups["value"].Value;
			item.IntroDuration = int.Parse(Regex.Match(infoHtml, @"introDuration\:(?<value>\d+),").Groups["value"].Value);
			string _lang= Uri.UnescapeDataString(Regex.Match(infoHtml, "languages\\:\\\"(?<value>[^\\\"]*)\\\",").Value);
			foreach (Match langMatch in Regex.Matches(_lang, "\\\"LanguageCode\\\"\\:\\\"(?<value>\\w+)\\\""))
				item.Languages.Add(langMatch.Groups["value"].Value);

			return item;
		}

		public static string GetHttpHtml(string url)
		{
			HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
			HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
			string html = new StreamReader(resp.GetResponseStream(), Encoding.UTF8).ReadToEnd();
			resp.Close();
			return html;
		}
	}
}